<?php
function php_file_tree($directory) {
  // Generates a valid XHTML list of all directories, sub-directories, and files in $directory
  // Remove trailing slash
  $code ='';
  if( substr($directory, -1) == "/" ) $directory = substr($directory, 0, strlen($directory) - 1);
  $code .= php_file_tree_dir($directory, $directory);
  return $code;
}

function php_file_tree_dir($directory, $basedir, $first_call = true) {
  // Recursive function called by php_file_tree() to list directories/files
  $php_file_tree = '';
  // Get and sort directories/files
  $file = @scandir($directory); natcasesort($file);
  // Make directories first
  $dirs = array();
  foreach($file as $this_file) {
    if(is_dir("$directory/$this_file")) {
      $dirs[] = $this_file;
    }
  }
  $file = $dirs;
  // Do Removals
  $removals = (!isset($_REQUEST['files'])) ? array() : $_REQUEST['files'];
  if(count($removals) > 0) {
    array_walk($removals, create_function('&$v, $k, $basedir', '{ $v = "$basedir$v"; }'), $basedir);
    foreach($file as $key=>$fvalue) {
      if(in_array("$directory/$fvalue", $removals))
      unset($file[$key]);
    }
  }
  
  // Recursive
  if( count($file) > 2 ) {
    // Use 2 instead of 0 to account for . and .. "directories"
    $php_file_tree = "<ul";
    if( $first_call ) { $php_file_tree .= " class=\"php-file-tree\""; $first_call = false; }
    $php_file_tree .= ">";
    foreach( $file as $this_file ) {
      if( $this_file != "." && $this_file != ".." ) {
        // Directory
        $value = str_replace($basedir, '', "$directory/$this_file");
        $php_file_tree .= "<li class=\"pft-directory\"><input type=\"radio\" name=\"folder\" value=\"$value\"/><a href=\"#\">" . htmlspecialchars($this_file) . "</a>";
        $php_file_tree .= php_file_tree_dir("$directory/$this_file", $basedir, false);
        $php_file_tree .= "</li>";
      }
    }
    $php_file_tree .= "</ul>";
  }
  return $php_file_tree;
}
    
function GetSubFolders($cdir) {
		if(strlen(php_file_tree($cdir))>5)
		echo "<form id=\"Form1\">".php_file_tree($cdir)."</form>"; 
		else echo "<br/>No other subfolders found in this location!";
}

require_once('../../conf/main.conf.php');
if(isset($_REQUEST['dir']) && !empty($_REQUEST['dir'])) {
  GetSubFolders($_SESSION['dir']);
}
?>
